package com.atlige.gzmall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atlige.common.utils.HttpUtils;
import com.atlige.common.utils.R;
import com.atlige.common.vo.MemberRespVo;
import com.atlige.gzmall.auth.feign.MemberFeignService;
import com.atlige.gzmall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jeremy Li
 * @data 2021/4/1 - 15:28
 */
@Controller
@Slf4j
public class OAuth2Controller {
    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        // 1、根据code换取accessToken
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "3859441149");
        map.put("client_secret", "78e4c3612e8d081299afe3167dcae600");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gzmall.com/oauth2.0/weibo/success");
        map.put("code", code);
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<String, String>(), null, map);
        // 处理
        if (response.getStatusLine().getStatusCode() == 200){
            //获取accessToken
            String toString = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(toString, SocialUser.class);
            // 知道当前是哪个会员
            // 1、第一次登录网站则自动进行注册
            R oauthlogin = memberFeignService.oauthlogin(socialUser);
            if (oauthlogin.getCode() == 0){
                MemberRespVo respVo = oauthlogin.getData(new TypeReference<MemberRespVo>() {
                });
                log.info("登陆成功：用户：{}", respVo.toString());
                // 1.第一次使用session命令服务器保存JSESSIONID这个cookie
                // 以后浏览器方位哪个网站都会带上这个cookie
                // gzmall.com, auth.gzmall.com
                // TODO 1.解决子域session问题
                // TODO 2.使用json序列化方式把对象序列化到redis
                session.setAttribute("loginUser", respVo);
                return "redirect:http://gzmall.com";
            }else {
                return "redirect:http://auth.gzmall.com/login.html";
            }
        }else {
            return "redirect:http://auth.gzmall.com/login.html";
        }
        // 2、登陆成功就跳回首页
    }
}
